﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Microsoft.Office.Interop.Excel;
using PublicClass;
using System;
using System.Windows.Forms;

namespace PublicTool1
{
    public class CmdEntry : IExtensionApplication
    {
        public void Initialize()
        {
        }

        public void Terminate()
        {
        }
        /// <summary>
        /// 有规律的散乱实体批量制作图块
        /// </summary>
        [CommandMethod("PublicTool1_BatMakeBlk")]
        public static void PublicTool1_BatMakeBlk()
        {
            SameEntsToBlk sameEntsToBlk = new SameEntsToBlk();

            // 1.框选实体（高级搜索，可以根据图层等等进行过滤）
            // 2.构造四叉树 加速搜索（CAD：14之前的版本 ，如果所搜索实体不在视口内是搜索不到的）
            // 3.选择一组实体作为参照，来找到相同的实体组(然后隐藏掉先)
            sameEntsToBlk.Go();
// 
//             // 思路：选择一组实体作为参照，来找到相同的实体组(然后隐藏掉先)
//             // 然后依次类推
            while (sameEntsToBlk.OneGroupDo())
            {
                ;
            }
// 
            sameEntsToBlk.DoBlk(); // 批量做图块 相同的做一个图块 显示多个块引用
        }

        enum CellHorizonAlignment
        {
            xlHAlignCenter = -4108,
            xlHAlignCenterAcrossSelection = 7,
            xlHAlignDistributed = -4117,
            xlHAlignFill = 5,
            xlHAlignGeneral = 1,
            xlHAlignJustify = -4130,
            xlHAlignLeft = -4131,
            xlHAlignRight = -4152
        };
        enum CellVerticalAlignment
        {
            xlVAlignBottom = -4107,
            xlVAlignCenter = -4108,
            xlVAlignDistributed = -4117,
            xlVAlignJustify = -4130,
            xlVAlignTop = -4160
        };
        /// <summary>
        /// 写入Excel
        /// </summary>
        [CommandMethod("PublicTool1_Excel")]
        public static void PublicTool1_Excel()
        {
            bool bShowExcel = true; //在程序运行时不被提示和警报消息打扰
            var ExcelApp = new Microsoft.Office.Interop.Excel.Application();
            ExcelApp.DisplayAlerts = false;
            ExcelApp.Visible = bShowExcel;  // 是否显示Excel
            Workbook book = null;     // 一个Excel文件
            Worksheet wb = null;// 一个sheet页面
            for (int i = 0; i < 3; i++)
            {
                string str = "Sheet" + i.ToString();
                if (0 == i)
                {
                    // 创建一个Excel文件对象
                    book = ExcelApp.Workbooks.Add(
                                        Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                   // 默认有一个sheet
                    wb = book.ActiveSheet;
                }
                else
                {
                    // 增加一个sheet
                    wb = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add(
                        Type.Missing, wb, Type.Missing, Type.Missing);
                    // 置为当前
                    wb.Activate();
                }
                wb.Name = str;
                int countRow = 10;
                int countCol = 5;
                // 设置需要的操作范围Range,可以统一设置字体等，我之里啥也没干
                Range range = wb.Range[wb.Cells[0 + 1, 0 + 1], wb.Cells[countRow + 1, countCol + 1]];
                for (int row = 0;row < countRow; ++row)
                {
                    for (int col = 0;col < countCol; ++col)
                    {
                        range = wb.Range[wb.Cells[row + 1, col + 1], wb.Cells[row + 1, col + 1]];
                        range.Value = string.Format($"({row},{col})-{str}");
                        range.NumberFormatLocal = "@"; // 以文字显示数字
                        range.Font.Size = 11; // 文字高度
                        range.Font.Name = "宋体"; // 文字样式
                        // 文字对中
                        range.VerticalAlignment = CellVerticalAlignment.xlVAlignCenter;
                        range.HorizontalAlignment = CellHorizonAlignment.xlHAlignCenter;
                    }
                }
            }

            try
            {
                //设置新建表格的保存路径以及名称
                ExcelApp.ActiveWorkbook.SaveAs("D:\\1.xlsx");
                if (bShowExcel)
                    ExcelApp.Visible = bShowExcel;
                else
                {
                    ExcelApp.Quit();
                    ExcelApp = null;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("创建表格失败" + ex.Message);
            }

        }

        /// <summary>
        /// 表格方向
        /// </summary>
        public enum ETableDir
        {
            eDown = 0,          // 往下绘制
            eUp,                // 往上绘制
        };

        /// <summary>
        /// 写入CadTable
        /// </summary>
        [CommandMethod("PublicTool1_CadTable")]
        public static void PublicTool1_CadTable()
        {
            var mTable = new Table();
            mTable.TableStyle = CadUnits.CreateWTableStyle();
            // 表格方向,这里不知道是我找错位置了还是API本身有问题，FlowDirection本身的定义有问题，这里找到的是MText的方向，不是Table的方向
            mTable.FlowDirection = (Autodesk.AutoCAD.DatabaseServices.FlowDirection)ETableDir.eDown;
            // mTable.Position; // 表格插入点
            //  mTable.TransformBy();
            // 生成布局
            mTable.GenerateLayout();
            int row = 10;
            int col = 10;
            // 表格初始化行列
            mTable.SetSize(row, col);
            var Cols = mTable.Columns;
            for (int i = 0;i < col;++i)
            {
                Cols[i].Width = 40;
            }

            for (int i = 0; i < row; ++i)
            {
                Row rowData = mTable.Rows[i];
                rowData.Height = 13;

                for (int j = 0; j < col; j++)
                {
                    Cell cell = mTable.Cells[i, j];
//                     if (cell.Contents.Count == 0)
//                         cell.Contents.Add();
                    cell.TextHeight = 10;
                    cell.TextString = string.Format($"({i},{j})");

                    // cell.BlockTableRecordId // 单元格内显示图块时使用
                    // cell.Contents[0].Scale = 1;
                }

            }

            // 合并单元格 (合并第一行)
            CellRange range = CellRange.Create(mTable, 0, 0,
                0, col - 1);
            mTable.MergeCells(range);


            CadUnits.AppendEntity(mTable);
        }
    }
}
